import { queryFamily } from "@/api/love.api";
import { Family, LoveTime } from "@/types/Family";

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { timeDiff } from "@/utils/useTimeDiff";
import { useEffect, useState } from "react";
export const useLove = (): {
  love: Family;
  timeLen: LoveTime;
  getFamily: () => void;
} => {
  const [love, setLove] = useState<Family>(new Family());
  const [timeLen, setTimeLen] = useState<LoveTime>(new LoveTime());
  /**
   * 获取表白墙信息
   */
  const getFamily = async () => {
    const res = await queryFamily();
    if (res.code === 200) {
      setLove(res.data || new Family());
      if (!love.timing) {
        setTimeLen(new LoveTime());
      }
    }
  };
  useEffect(() => {
    getFamily();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useEffect(() => { 
    const timerId = setInterval(() => {
      if (love.timing) {
        const {
          diffYear: year,
          diffMonth: month,
          diffDay: day,
          diffHour: hour,
          diffMinute: minute,
          diffSecond: second,
        } = timeDiff(love.timing);

        setTimeLen({
          year,
          month,
          day,
          hour,
          minute,
          second,
        });
      }
    }, 1000);
    if(!love.timing&&timerId) clearInterval(timerId)
    return () => {
      clearInterval(timerId);
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [love.timing]);
  return {
    love,
    getFamily,
    timeLen,
  };
};
